package com.futu.common.intercepters;


import com.futu.common.annotation.NoLoginRequired;
import com.futu.common.contans.CommonContants;

import com.futu.common.exceptions.ApiException;
import com.futu.common.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
@Slf4j
public class AuthIntercepter implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;



    public final static  String Token="token";

    public AuthIntercepter() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle)
    {

        String token  = request.getHeader(Token);
        System.err.println(token);
        log.info(request.getRequestURI());
        try {
            if (!(handle instanceof HandlerMethod))
            {
                return true;
            }
            HandlerMethod handlerMethod=(HandlerMethod)handle;
            Method method = handlerMethod.getMethod();
            NoLoginRequired loginRequired = method.getAnnotation(NoLoginRequired.class);
            if (loginRequired!=null)
            {
                return true;
            }
            if (StringUtils.isEmpty(token))
            {
                log.info("token为空");
                throw new Exception("token错误,请重新登录");
            }
            Long userId = TokenUtils.getUserId(token);
            log.info("userId",userId);
            Object user = redisTemplate.opsForValue().get("user"+userId);
            if (user==null)
            {
                log.info("*************用户不存在");
                throw new ApiException(101,"token错误");
            }
            CommonContants.local.set(userId.toString());


        } catch (Exception e) {
            log.info("调用了异常通知",e.getMessage());
            throw new RuntimeException(e);
        }
        return true;
    }
}
